using System;
using System.Collections.Generic;
using System.Text;

namespace Acms.Bll
{
    public class UserPrinciple : System.Security.Principal.IPrincipal
    {
        private UserPrinciple(UserIdentity identity, Guid key)
        {
            this.identity = identity;
            this.key = key;
        }

        public static UserPrinciple Construct(Guid key)
        {
            User tmp = User.GetFromLoginKey(key);
            if(tmp != null)
            {
                return new UserPrinciple(new UserIdentity(tmp), key);
            }
            else
            {
                return null;
            }
        }

        private Guid key;
    
        private UserIdentity identity;
        public UserIdentity Identity
        {
	        get { return identity; }
        }

        public bool  IsInRole(string role)
        {
            return false;
        }

        #region IPrincipal Members

        System.Security.Principal.IIdentity System.Security.Principal.IPrincipal.Identity
        {
            get { return this.Identity; }
        }

        bool System.Security.Principal.IPrincipal.IsInRole(string role)
        {
            return false;
        }

        public void Logout()
        {
            Identity.User.DeleteLoginKey(key);
            System.Web.Security.FormsAuthentication.SignOut();
        }
        #endregion
    }

    public class UserIdentity : System.Security.Principal.IIdentity
    {
        public UserIdentity(User user)
        {
            if(!user.IsNewRecord)
            {
                this.user = user;
            }
        }

        private User user;
        public User User
        {
            get { return user; }
        }
        
        public string  AuthenticationType
        {
	        get { return "Forms"; }
        }

        public bool  IsAuthenticated
        {
	        get { return user != null; }
        }

        public string  Name
        {
	        get 
            {
                return user == null ? null : user.UserName;
            }
        }


        public void RefreshUser()
        {
            user = User.GetById(user.Id);
        }
    }
}
